import { useState, useEffect } from 'react';
import { useLanguage } from '@kernelproxy/i18n';
import { Button } from '@kernelproxy/ui';
import { authService } from '../services/auth';
import { Monitor, Smartphone, Clock, MapPin, AlertCircle } from 'lucide-react';
import { Models } from 'appwrite';

const SessionManagement = () => {
  const [sessions, setSessions] = useState<Models.Session[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const { language } = useLanguage();

  useEffect(() => {
    loadSessions();
  }, []);

  const loadSessions = async () => {
    setLoading(true);
    setError('');

    try {
      const result = await authService.listSessions();
      if (result.success && result.sessions) {
        setSessions(result.sessions.sessions);
      } else {
        setError(language === 'zh-CN' ? '加载会话失败' : 'Failed to load sessions');
      }
    } catch (err) {
      setError(language === 'zh-CN' ? '加载会话失败' : 'Failed to load sessions');
    } finally {
      setLoading(false);
    }
  };

  const handleLogoutSession = async (sessionId: string) => {
    if (!confirm(language === 'zh-CN' ? '确定要登出此设备吗？' : 'Are you sure you want to log out this device?')) {
      return;
    }

    try {
      const result = await authService.deleteSession(sessionId);
      if (result.success) {
        // Reload sessions
        await loadSessions();
      } else {
        setError(language === 'zh-CN' ? '登出失败' : 'Failed to log out');
      }
    } catch (err) {
      setError(language === 'zh-CN' ? '登出失败' : 'Failed to log out');
    }
  };

  const handleLogoutAll = async () => {
    if (!confirm(language === 'zh-CN' ? '确定要登出所有设备吗？这将结束您在所有设备上的会话。' : 'Are you sure you want to log out all devices? This will end your session on all devices.')) {
      return;
    }

    try {
      const result = await authService.logoutAll();
      if (result.success) {
        window.location.href = '/login';
      } else {
        setError(language === 'zh-CN' ? '登出失败' : 'Failed to log out');
      }
    } catch (err) {
      setError(language === 'zh-CN' ? '登出失败' : 'Failed to log out');
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString(language === 'zh-CN' ? 'zh-CN' : 'en-US');
  };

  const getDeviceIcon = (deviceName: string) => {
    const name = deviceName.toLowerCase();
    if (name.includes('mobile') || name.includes('iphone') || name.includes('android')) {
      return <Smartphone className="w-6 h-6" />;
    }
    return <Monitor className="w-6 h-6" />;
  };

  const isExpiringSoon = (expireDate: string) => {
    const expire = new Date(expireDate).getTime();
    const now = Date.now();
    const timeUntilExpiry = expire - now;
    return timeUntilExpiry < 60 * 60 * 1000; // Less than 1 hour
  };

  return (
    <div className="max-w-4xl mx-auto p-6">
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
          {language === 'zh-CN' ? '会话管理' : 'Session Management'}
        </h1>
        <p className="mt-2 text-gray-600 dark:text-gray-400">
          {language === 'zh-CN' 
            ? '查看和管理您的活动会话' 
            : 'View and manage your active sessions'}
        </p>
      </div>

      {error && (
        <div className="mb-4 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md flex items-start gap-2">
          <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
          <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
        </div>
      )}

      <div className="mb-6 flex justify-end">
        <Button onClick={handleLogoutAll} variant="outline" size="sm">
          {language === 'zh-CN' ? '登出所有设备' : 'Log Out All Devices'}
        </Button>
      </div>

      {loading ? (
        <div className="text-center py-12">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-[#00d4ff]"></div>
        </div>
      ) : (
        <div className="space-y-4">
          {sessions.length === 0 ? (
            <div className="text-center py-12 bg-white dark:bg-gray-800 rounded-lg">
              <p className="text-gray-600 dark:text-gray-400">
                {language === 'zh-CN' ? '没有活动会话' : 'No active sessions'}
              </p>
            </div>
          ) : (
            sessions.map((session) => (
              <div 
                key={session.$id} 
                className={`bg-white dark:bg-gray-800 p-6 rounded-lg shadow ${
                  session.current ? 'border-2 border-[#00d4ff]' : ''
                }`}
              >
                <div className="flex items-start justify-between">
                  <div className="flex items-start gap-4 flex-1">
                    <div className="text-gray-600 dark:text-gray-400">
                      {getDeviceIcon(session.deviceName || 'Unknown')}
                    </div>
                    
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                          {session.deviceName || (language === 'zh-CN' ? '未知设备' : 'Unknown Device')}
                        </h3>
                        {session.current && (
                          <span className="px-2 py-1 bg-[#00d4ff]/10 text-[#00d4ff] text-xs font-medium rounded">
                            {language === 'zh-CN' ? '当前设备' : 'Current'}
                          </span>
                        )}
                        {isExpiringSoon(session.expire) && !session.current && (
                          <span className="px-2 py-1 bg-yellow-100 dark:bg-yellow-900/20 text-yellow-800 dark:text-yellow-200 text-xs font-medium rounded">
                            {language === 'zh-CN' ? '即将过期' : 'Expiring Soon'}
                          </span>
                        )}
                      </div>
                      
                      <div className="space-y-1 text-sm text-gray-600 dark:text-gray-400">
                        <div className="flex items-center gap-2">
                          <Monitor className="w-4 h-4" />
                          <span>{session.osName} • {session.clientName}</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <MapPin className="w-4 h-4" />
                          <span>
                            {session.countryName || (language === 'zh-CN' ? '未知位置' : 'Unknown Location')}
                            {session.ip && ` • ${session.ip}`}
                          </span>
                        </div>
                        <div className="flex items-center gap-2">
                          <Clock className="w-4 h-4" />
                          <span>
                            {language === 'zh-CN' ? '最后活动：' : 'Last active: '}
                            {formatDate(session.$createdAt)}
                          </span>
                        </div>
                        <div className="flex items-center gap-2 text-xs">
                          <Clock className="w-4 h-4" />
                          <span>
                            {language === 'zh-CN' ? '过期时间：' : 'Expires: '}
                            {formatDate(session.expire)}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>

                  {!session.current && (
                    <Button 
                      onClick={() => handleLogoutSession(session.$id)}
                      variant="outline"
                      size="sm"
                    >
                      {language === 'zh-CN' ? '登出' : 'Log Out'}
                    </Button>
                  )}
                </div>
              </div>
            ))
          )}
        </div>
      )}

      <div className="mt-8 p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
        <h4 className="font-semibold text-blue-900 dark:text-blue-200 mb-2">
          {language === 'zh-CN' ? '安全提示' : 'Security Tip'}
        </h4>
        <p className="text-sm text-blue-800 dark:text-blue-300">
          {language === 'zh-CN' 
            ? '定期检查您的活动会话。如果发现不认识的设备，请立即登出并更改密码。' 
            : 'Regularly review your active sessions. If you see an unfamiliar device, log it out immediately and change your password.'}
        </p>
      </div>
    </div>
  );
};

export default SessionManagement;
